package org.nnxy.foodboot.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.nnxy.foodboot.entity.*;
import org.nnxy.foodboot.service.RecipeService;
import org.nnxy.foodboot.service.RecipeStepService;
import org.nnxy.foodboot.service.UserBrowseHistoryService;

import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 食谱控制器
 */
@RestController
@RequestMapping("/api/recipe")
@RequiredArgsConstructor
public class RecipeController {
    
    private final RecipeService recipeService;
    private final RecipeStepService recipeStepService;
    private final UserBrowseHistoryService userBrowseHistoryService;

    
    /**
     * 分页查询食谱列表
     */
    @GetMapping("/page")
    public Map<String, Object> page(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String flavor,
            @RequestParam(required = false) String technique,
            @RequestParam(required = false) String duration,
            @RequestParam(required = false) String difficulty) {
        
        // 构建查询条件
        LambdaQueryWrapper<Recipe> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.hasText(name)) {
            queryWrapper.like(Recipe::getName, name);
        }
        if (StringUtils.hasText(flavor)) {
            queryWrapper.eq(Recipe::getFlavor, flavor);
        }
        if (StringUtils.hasText(technique)) {
            queryWrapper.eq(Recipe::getTechnique, technique);
        }
        if (StringUtils.hasText(duration)) {
            queryWrapper.eq(Recipe::getDuration, duration);
        }
        if (StringUtils.hasText(difficulty)) {
            queryWrapper.eq(Recipe::getDifficulty, difficulty);
        }
        
        // 按创建时间降序排序
        queryWrapper.orderByDesc(Recipe::getCreateTime);
        
        // 分页查询
        Page<Recipe> page = recipeService.page(new Page<>(current, size), queryWrapper);
        
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("data", page);
        return result;
    }
    
    /**
     * 获取食谱详情
     */
    @GetMapping("/{id}")
    public Map<String, Object> getById(@PathVariable Integer id, @RequestParam(required = false) Integer userId) {
        Map<String, Object> result = new HashMap<>();
        
        // 获取食谱信息，不再强制检查登录状态
        Recipe recipe = recipeService.getById(id);
        
        // 判断食谱是否存在
        if (recipe == null) {
            result.put("code", 404);
            result.put("message", "食谱不存在");
            return result;
        }
        
        // 查询指定食谱的步骤列表
        LambdaQueryWrapper<RecipeStep> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RecipeStep::getRecipeId, id)
                .orderByAsc(RecipeStep::getStepNumber); // 按步骤顺序排序
        
        List<RecipeStep> steps = recipeStepService.list(queryWrapper);
        
        Map<String, Object> data = new HashMap<>();
        data.put("recipe", recipe);
        data.put("steps", steps);
        
        // 如果用户已登录，记录用户浏览历史
        if (userId != null) {
            // 初始浏览时长为0，后续前端可能会更新
            userBrowseHistoryService.addBrowseHistory(userId, id, 0);
        }
        
        result.put("code", 200);
        result.put("data", data);
        return result;
    }
    
    /**
     * 新增食谱
     */
    @PostMapping
    public Map<String, Object> save(@RequestBody Recipe recipe) {
        boolean success = recipeService.save(recipe);
        
        Map<String, Object> result = new HashMap<>();
        if (success) {
            result.put("code", 200);
            result.put("message", "添加成功");
            result.put("data", recipe); // 返回保存后的食谱，包含ID
        } else {
            result.put("code", 500);
            result.put("message", "添加失败");
        }
        return result;
    }
    
    /**
     * 修改食谱
     */
    @PutMapping
    public Map<String, Object> update(@RequestBody Recipe recipe) {
        boolean success = recipeService.updateById(recipe);
        
        Map<String, Object> result = new HashMap<>();
        if (success) {
            result.put("code", 200);
            result.put("message", "修改成功");
        } else {
            result.put("code", 500);
            result.put("message", "修改失败");
        }
        return result;
    }
    
    /**
     * 删除食谱
     */
    @DeleteMapping("/{id}")
    public Map<String, Object> remove(@PathVariable Integer id) {
        boolean success = recipeService.removeById(id);
        
        Map<String, Object> result = new HashMap<>();
        if (success) {
            result.put("code", 200);
            result.put("message", "删除成功");
        } else {
            result.put("code", 500);
            result.put("message", "删除失败");
        }
        return result;
    }
    
    /**
     * 获取食谱的筛选条件（口味、工艺、耗时、难度）
     */
    @GetMapping("/filters")
    public Map<String, Object> getFilters() {
        Map<String, Object> filters = new HashMap<>();
        
        // 模拟数据，实际可以从数据库中查询
        filters.put("flavors", List.of("咸鲜味", "甜味", "酸甜味", "麻辣味", "香辣味", "五香味"));
        filters.put("techniques", List.of("炒", "蒸", "煮", "炖", "煎", "烤", "炸"));
        filters.put("durations", List.of("10分钟以内", "10-30分钟", "30-60分钟", "1-2小时", "2小时以上"));
        filters.put("difficulties", List.of("新手尝试", "初级入门", "中级掌勺", "高级厨师"));
        
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("data", filters);
        return result;
    }
    
    /**
     * 获取食谱的制作步骤
     */
    @GetMapping("/{id}/steps")
    public Map<String, Object> getRecipeSteps(@PathVariable Integer id) {
        // 先检查食谱是否存在
        Recipe recipe = recipeService.getById(id);
        
        Map<String, Object> result = new HashMap<>();
        
        // 判断食谱是否存在
        if (recipe == null) {
            result.put("code", 404);
            result.put("message", "食谱不存在");
            return result;
        }
        
        // 查询指定食谱的步骤列表
        LambdaQueryWrapper<RecipeStep> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RecipeStep::getRecipeId, id)
                .orderByAsc(RecipeStep::getStepNumber); // 按步骤顺序排序
        
        List<RecipeStep> steps = recipeStepService.list(queryWrapper);
        
        result.put("code", 200);
        result.put("data", steps);
        return result;
    }
    

} 